﻿using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Engines;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BenchMarkTest
{
    // 添加内存分析+排名字段
    [MemoryDiagnoser,RankColumn]
    public class MemoryBenchmarker
    {
        int NumberOfItems = 100000;

        // 简单问题：下面代码创建了几个对象? 内存里面有字符串常量池->地址引用
        //string a = "gerry";
        //string b = "gerry";
        //string c = a + b;
        //string d = "gerrygerry";
        //

        [Benchmark]
        public string ConcatStringsUsingOperator()
        {
            string str = "";
            for (int i = 0; i < NumberOfItems; i++)
            {
                str += ("Hello World!" + i).ToString();
            }
            return str;
        }

        [Benchmark]
        public string ConcatStringsUsingStringBuilder()
        {
            var sb = new StringBuilder();
            for (int i = 0; i < NumberOfItems; i++)
            {
                sb.Append("Hello World!" + i);
            }
            return sb.ToString();
        }

        [Benchmark]
        public string ConcatStringsUsingGenericList()
        {
            var list = new List<string>(NumberOfItems);
            for (int i = 0; i < NumberOfItems; i++)
            {
                list.Add("Hello World!" + i);
            }
            return list.ToString()!;
        }
    }
}
